const HotelRoom = require('../models/HotelRoom');
const { getStoreById } = require('../models/Store');

/**
 * 获取酒店房间列表
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 */
const getRooms = async (req, res) => {
    try {
        const { storeId } = req.params;
        
        // 验证店铺是否存在且类型为住宿
        const store = await getStoreById(storeId);
        if (!store) {
            return res.status(404).json({
                success: false,
                message: '店铺不存在'
            });
        }
        
        if (store.type !== '住宿') {
            return res.status(400).json({
                success: false,
                message: '该店铺不是酒店类型'
            });
        }
        
        const rooms = await HotelRoom.getRoomsByStoreId(storeId);
        
        res.json({
            success: true,
            data: rooms
        });
    } catch (error) {
        console.error('[CONTROLLER] 获取酒店房间列表失败:', error);
        res.status(500).json({
            success: false,
            message: '获取酒店房间列表失败'
        });
    }
};

/**
 * 获取酒店房间详情
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 */
const getRoomDetail = async (req, res) => {
    try {
        const { roomId } = req.params;
        
        const room = await HotelRoom.getRoomById(roomId);
        if (!room) {
            return res.status(404).json({
                success: false,
                message: '房间不存在'
            });
        }
        
        res.json({
            success: true,
            data: room
        });
    } catch (error) {
        console.error('[CONTROLLER] 获取酒店房间详情失败:', error);
        res.status(500).json({
            success: false,
            message: '获取酒店房间详情失败'
        });
    }
};

/**
 * 检查房间可用性
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 */
const checkRoomAvailability = async (req, res) => {
    try {
        const { roomId } = req.params;
        const { checkInDate, checkOutDate } = req.query;
        
        if (!checkInDate || !checkOutDate) {
            return res.status(400).json({
                success: false,
                message: '入住日期和退房日期不能为空'
            });
        }
        
        const room = await HotelRoom.getRoomById(roomId);
        if (!room) {
            return res.status(404).json({
                success: false,
                message: '房间不存在'
            });
        }
        
        const isAvailable = await HotelRoom.checkRoomAvailability(roomId, checkInDate, checkOutDate);
        
        res.json({
            success: true,
            data: {
                isAvailable,
                room
            }
        });
    } catch (error) {
        console.error('[CONTROLLER] 检查房间可用性失败:', error);
        res.status(500).json({
            success: false,
            message: '检查房间可用性失败'
        });
    }
};

/**
 * 创建房间预订
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 */
const createBooking = async (req, res) => {
    try {
        const userId = req.user.userId;
        const { roomId } = req.params;
        const { 
            checkInDate, 
            checkOutDate, 
            guestName, 
            guestPhone, 
            isDepositOnly 
        } = req.body;
        
        if (!checkInDate || !checkOutDate || !guestName || !guestPhone) {
            return res.status(400).json({
                success: false,
                message: '请填写完整的预订信息'
            });
        }
        
        // 获取房间信息
        const room = await HotelRoom.getRoomById(roomId);
        if (!room) {
            return res.status(404).json({
                success: false,
                message: '房间不存在'
            });
        }
        
        // 检查房间是否可预订
        const isAvailable = await HotelRoom.checkRoomAvailability(roomId, checkInDate, checkOutDate);
        if (!isAvailable) {
            return res.status(400).json({
                success: false,
                message: '该时间段房间已被预订'
            });
        }
        
        // 计算入住天数
        const checkIn = new Date(checkInDate);
        const checkOut = new Date(checkOutDate);
        const days = Math.ceil((checkOut - checkIn) / (1000 * 60 * 60 * 24));
        
        if (days <= 0) {
            return res.status(400).json({
                success: false,
                message: '入住日期必须早于退房日期'
            });
        }
        
        // 计算价格
        const price = room.price;
        const totalPrice = price * days;
        
        // 计算定金（通常为总价的30%）
        const depositAmount = isDepositOnly ? Math.round(totalPrice * 0.3) : 0;
        
        // 创建预订
        const bookingData = {
            user_id: userId,
            room_id: roomId,
            store_id: room.store_id,
            check_in_date: checkInDate,
            check_out_date: checkOutDate,
            guest_name: guestName,
            guest_phone: guestPhone,
            price: totalPrice,
            deposit_amount: depositAmount,
            status: 'pending' // 待支付
        };
        
        const bookingId = await HotelRoom.createBooking(bookingData);
        
        res.status(201).json({
            success: true,
            data: {
                bookingId,
                totalPrice,
                depositAmount,
                paymentAmount: isDepositOnly ? depositAmount : totalPrice
            },
            message: '预订创建成功，请继续完成支付'
        });
    } catch (error) {
        console.error('[CONTROLLER] 创建房间预订失败:', error);
        res.status(500).json({
            success: false,
            message: '创建房间预订失败'
        });
    }
};

/**
 * 获取用户的预订列表
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 */
const getUserBookings = async (req, res) => {
    try {
        const userId = req.user.userId;
        
        const bookings = await HotelRoom.getUserBookings(userId);
        
        res.json({
            success: true,
            data: bookings
        });
    } catch (error) {
        console.error('[CONTROLLER] 获取用户预订列表失败:', error);
        res.status(500).json({
            success: false,
            message: '获取用户预订列表失败'
        });
    }
};

/**
 * 获取店铺的预订列表（商家接口）
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 */
const getStoreBookings = async (req, res) => {
    try {
        const { storeId } = req.params;
        
        // 验证当前用户是否为该店铺的所有者
        const userId = req.user.userId;
        const store = await getStoreById(storeId);
        
        if (!store || store.owner_id !== userId) {
            return res.status(403).json({
                success: false,
                message: '无权访问该店铺的预订信息'
            });
        }
        
        const bookings = await HotelRoom.getStoreBookings(storeId);
        
        res.json({
            success: true,
            data: bookings
        });
    } catch (error) {
        console.error('[CONTROLLER] 获取店铺预订列表失败:', error);
        res.status(500).json({
            success: false,
            message: '获取店铺预订列表失败'
        });
    }
};

/**
 * 更新预订状态
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 */
const updateBookingStatus = async (req, res) => {
    try {
        const { bookingId } = req.params;
        const { status } = req.body;
        
        if (!status) {
            return res.status(400).json({
                success: false,
                message: '状态不能为空'
            });
        }
        
        // 验证状态值是否合法
        const validStatuses = ['pending', 'paid', 'confirmed', 'cancelled', 'completed', 'refunded'];
        if (!validStatuses.includes(status)) {
            return res.status(400).json({
                success: false,
                message: '无效的状态值'
            });
        }
        
        await HotelRoom.updateBookingStatus(bookingId, status);
        
        res.json({
            success: true,
            message: '预订状态更新成功'
        });
    } catch (error) {
        console.error('[CONTROLLER] 更新预订状态失败:', error);
        res.status(500).json({
            success: false,
            message: '更新预订状态失败'
        });
    }
};

module.exports = {
    getRooms,
    getRoomDetail,
    checkRoomAvailability,
    createBooking,
    getUserBookings,
    getStoreBookings,
    updateBookingStatus
}; 